package com.lz.yz.outing.service;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class SyncLockService {

    @Resource(name = "redisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 分布式锁 控制并发
     *
     * @param key     缓存的key
     * @param timeout 时间
     * @param unit    时间单位
     * @return
     */
    public boolean syncLock(final String key, final long timeout, final TimeUnit unit) {
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        boolean lockFlag = ops.setIfAbsent(key, 1);
        if(lockFlag) {
            ops.set(key, 1, timeout, unit);
        }
        return lockFlag;
    }
}
